
import org.springframework.security.providers.UsernamePasswordAuthenticationToken as AuthToken
import org.springframework.security.context.SecurityContextHolder as SCH

/**
 * Registration controller.
 */
class RegisterController {

    def authenticateService
    def daoAuthenticationProvider
    def emailerService

    static Map allowedMethods = [save: 'POST', update: 'POST']

    /**
     * User Registration Top page.
     */
    def index = {

        // skip if already logged in
        if (!authenticateService.isLoggedIn() && session.id) {
            def user = new User()
            return [user: user]
        }

        redirect uri: '/'
    }

    /**
     * User save action.
     */
    def save = {

        // skip if already logged in
        if (authenticateService.isLoggedIn()) {
            redirect action: show
            return
        }

        def config = authenticateService.securityConfig
        def defaultRole = config.security.defaultRole
        def user = new User()
        user.properties = params

        def role = Role.findByAuthority(defaultRole)

        // Checking Role
        if (!role) {
            flash.message = "${message(code:"default.role.not.found.error")}"
            render view: 'index', model: [user: user]
            return
        }

        // Checking captcha codes for a match
        if (params.captcha.toUpperCase() != session.captcha) {
            user.errors.rejectValue('captcha', 'captcha.match.error')
        }

        if (!params.pass) {
            user.errors.rejectValue('pass', 'password.blank.error')
        }

        if (params.pass != params.confirmPass) {
            user.errors.rejectValue('pass', 'passwords.dont.match.error')
        }
        println user.errors

        // If the user has errors we go
        if (user.errors.hasErrors()) {
            user.pass= ''
            user.confirmPass = ''
            render view: 'index', model: [user: user]
            return
        }

        def pass = authenticateService.encodePassword(params.pass)
        user.password = pass
        user.enabled = true
        if (user.save(flush:true)) {
            role.addToUsers(user)
            if (config.security.useMail) {
                String emailContent = """You have signed up for an account at:
                        ${request.scheme}://${request.serverName}:${request.serverPort}${request.contextPath}
                        Here are the details of your account:
                        -------------------------------------
                        LoginName: ${user.username}
                        Email: ${user.primaryEmail}
                        First Name: ${user.firstName}
                        Last Name: ${user.LastName}
                        Password: ${params.password}
                        """

                def email = [
                    to: [user.primaryEmail], // 'to' expects a List, NOT a single email address
                    subject: "[${request.contextPath}] Account Signed Up",
                    text: emailContent // 'text' is the email body
                ]
                emailerService.sendEmails([email])
            }

            user.save(flush: true)

            def auth = new AuthToken(user.username, params.password)
            def authtoken = daoAuthenticationProvider.authenticate(auth)
            SCH.context.authentication = authtoken
            redirect uri: '/'
        } else {
            println "error after save"
            user.password = ''
            render view: 'index', model: [user: user]
//            redirect uri: '/user/show'
        }
    }
}
